package com.mianyang.zhangsan.service.impl;

import com.mianyang.zhangsan.common.util.StringUtils;
import com.mianyang.zhangsan.exception.SecServiceException;
import com.mianyang.zhangsan.model.entity.SecAccount;
import com.mianyang.zhangsan.model.entity.SecIdentity;
import com.mianyang.zhangsan.plugin.mail.Mail;
import com.mianyang.zhangsan.plugin.mail.MailSender;
import com.mianyang.zhangsan.service.ISecAccountService;
import com.mianyang.zhangsan.service.ISecIdentityService;
import com.mianyang.zhangsan.service.ISecMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;

/**
 * @author jiangjr
 * @date 2022-10-26
 */
@Component
public class SecMailServiceImpl implements ISecMailService {
    @Autowired
    private MailSender sender;
    @Autowired
    private ISecAccountService accountService;
    @Autowired
    private ISecIdentityService identityService;

    @Override
    public void sendMail(Long userId, Mail mail) throws SecServiceException, MessagingException {
        // 获取用户信息
        SecAccount account = accountService.getById(userId);
        SecIdentity identity = identityService.getById(account.getIdentityId());
        // 判断用户是否实名（邮箱认证）
        if (identity == null || StringUtils.isEmpty(identity.getMailAuth())) {
            throw new SecServiceException("请邮箱认证后重试");
        }
        // 发送邮件
        sender.init(identity.getRealMail(), identity.getMailAuth());
        sender.sendMessage(mail);
    }
}
